package com.lagou.client.handler;

import com.lagou.service.common.RpcEncoder;
import com.lagou.service.pojo.RpcRequest;
import com.lagou.service.seriallzer.JSONSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Administrator
 * @version 1.0
 * @date 2020/7/4 8:39
 * 消费者
 */
public class RPCConsumer {

    //创建一个线程池对象  -- 处理我们自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //申明一个自定义事件处理器
    private static UserClientHandler userClientHandler;

    //初始化客户端
    public static void initClient() throws InterruptedException {
        userClientHandler =new UserClientHandler();
        EventLoopGroup boos  = new NioEventLoopGroup();
        //创建客户端的引导对象
        Bootstrap bootstrap =new Bootstrap();
        bootstrap.group(boos)
                //设置通道为Nio
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听Channel并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast( new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        //连接服务端
          bootstrap.connect("127.0.0.1", 8999).sync();
    }


    //编写JDK动态代理
    public static Object createProxy(final Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //初始化客户端client
                if(userClientHandler == null){
                    //如果没有初始化，则初始化 userClientHandler
                    initClient();
                }
                RpcRequest request = new RpcRequest();
                request.setClassName(method.getDeclaringClass().getName());
                request.setMethodName(method.getName());
                request.setParameters(args);
                request.setRequestId(UUID.randomUUID().toString());
                request.setParameterTypes(method.getParameterTypes());

                userClientHandler.setParam(request);
                //给userClientHandler 设置param参数
                Object o = executorService.submit(userClientHandler).get();

                // 使用线程池开启一个线程处理cell写操作，并返回结果

                //return 结果
                return o;
            }
        });
    }
}
